import {asyncRoutes, constantRoutes} from '@/router'
import Layout from '@/layout'// 【新加入】引入layout
import {getMenu} from '@/api/user'
import {getLanguage} from '@/lang/index'

import store from '../../store'

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

// 这里自己写方法，作用就是向 asyncRoutes 插入路由，达到动态路由的效果
/**
 * 【新加入】后台查询的菜单数据拼装成路由格式的数据
 * @param routes
 */
export function generaMenu(routes, data) {
  console.log('制作路由')

  let lang = getLanguage();
  console.log("当前语言", lang)
  // data挨个遍历
  data.forEach(item => {
    // path不为空的话，就新建一个对象，装数据
    let title = item.title;
    if (lang == 'en' && item.en_title) {
      title = item.en_title;
    }
    const meta = {
      title: title,
      icon: item.icon,
      roles: item.roles// you can set roles in root nav
    }

    if (item.href !== '') {

      // 这个就仿照目录的机构，搭建
      const menu = {
        path: item.href,
        component: Layout, // 这个不用写data里面的内容，引用就行了
        redirect: '/',
        alwaysShow: true,
        children: [],
        name: title,
        meta: meta
      }
      // 遍历子标签，并加入到主目录的children中去
      item.children.forEach(item => {
        if (item.nav_type !== "按钮") {
          let title = item.title;
          if (lang == 'en' && item.en_title) {
            title = item.en_title;
          }
          const meta = {
            title: title,
            icon: item.icon,
            roles: item.roles// you can set roles in root nav
          }
          let menu2 = {
            path: item.href,
            component: null,
            name: title,
            meta: meta
          }
          try {
            require(`@/views${item.href}`)
            menu2.component = (resolve) => {
              require([`@/views${item.href}`], resolve)
            }
          } catch (e) {
            console.log('出错了', e)
            item.href = '/error-page/404'
            menu2.component = (resolve) => {
              require([`@/views${item.href}`], resolve)
            }
          }
          // 加入到主目录的children中去
          menu.children.push(menu2)
        } else {
          store.state.user.buttons.push(item.href);
          // console.log("此前的store", store.getters.buttons)
        }

        if(item.children&&item.children.length>0){
            item.children.forEach((it)=>{
              if(it.nav_type=="按钮"){
                store.state.user.buttons.push(it.href);
              }
            })
        }

      })
      // 追加
      routes.push(menu)
      // routes.push({
      //   path: '/share',
      //   component: () => import('@/views/bs/share'),
      //   hidden: true,
      //   meta: {
      //     title: '文件分享',
      //     requiresAuth: false
      //   }
      // })
    }
  })

  // 把404加到最后，因为作者说  // 404 page must be placed at the end !!!
  const menu3 = {
    path: '*',
    redirect: '/404',
    hidden: true
  }
  // 追加
  // routes.push(menu3)
  // const menu4 = {
  //   path: '/bs/sl_station_attr',
  //   component: () => import('@/views/bs/sl_station_attr'),
  //   name: 'sl_station_attr',
  //   meta: { title: '工位属性', icon: 'el-icon-office-building' }
  // }
  // routes.push(menu4)
  // console.log('路由', routes)
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = {...route}
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({commit}, roles) {
    return new Promise(resolve => {
      const loadMenuData = []
      // 先查询后台并返回左侧菜单数据并把数据添加到路由，authMenu（state.token）后面会写
      getMenu().then(response => {
        let data = response

        // 获取目录的json
        data = response.data

        // 把data的数据拷贝到loadMenuData里面
        Object.assign(loadMenuData, data)
        // 把asyncRoutes的数据拷贝到tempAsyncRoutes里面
        const tempAsyncRoutes = Object.assign([], asyncRoutes)
        // 最最重要的，把loadMenuData追加到tempAsyncRoutes后面
        generaMenu(tempAsyncRoutes, loadMenuData)
        console.log('路由1', tempAsyncRoutes)
        // 定义accessedRoutes
        let accessedRoutes
        // 把 tempAsyncRoutes 的值给 accessedRoutes ，并输出
        // eslint-disable-next-line prefer-const
        accessedRoutes = tempAsyncRoutes || []
        // 下面这些就是加载目录了
        commit('SET_ROUTES', accessedRoutes)
        resolve(accessedRoutes)
      })

      // let accessedRoutes
      // if (roles.includes('admin')) {
      //   accessedRoutes = asyncRoutes || []
      // } else {
      //   accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
      // }
      // commit('SET_ROUTES', accessedRoutes)
      // resolve(accessedRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
